package com.sat.order.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.sat.common.entity.Result;
import com.sat.goods.model.SkuVo;
import com.sat.order.model.OrderItem;
import com.sat.order.service.CartService;
import com.sat.user.model.User;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("cart")
public class CartController {

    @Autowired
    private CartService cartService;


    @GetMapping("all")
    public Result findAll(){
        // TODO  从工具类获取用户id
        String username = "admin";
        // 只能根据用户id查询购物车
        List<OrderItem> list =  redisTemplate.boundHashOps("cart_"+username).values();
        return Result.OK("查询成功",list);
    }

    @RequestMapping("delete/{skuId}")
    public Result delete(@PathVariable Long skuId){
        // TODO  从工具类获取用户id
        String username = "admin";
        redisTemplate.boundHashOps("cart_" + username).delete(skuId);
        return new Result();
    }



    // 加入购物车    skuId  商品数量

    /**
     * @param skuId  sku id
     * @param num    加入购物车的商品数量
     * @param isLogin  1 /登录   0 代表未登录  只是模拟测试登录功能
     * @return
     */
    @RequestMapping("add")
    public Result add(Long skuId , Integer num,Integer isLogin, HttpServletRequest request, HttpServletResponse response){
        // 判断是否登录
        // 通过工具类  获取用户信息  如果用户信息为空 说明没有登录
        // 模拟没有登录的数据 TODO
        // 获取用户信息 TODO
        User user = new User();
        user = null;
        SkuVo skuVo =  cartService.findBySkuId(skuId);

        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(skuVo.getSpu().getCategory1Id());
        orderItem.setCategoryId2(skuVo.getSpu().getCategory2Id());
        orderItem.setCategoryId3(skuVo.getSpu().getCategory3Id());
        orderItem.setSpuId(skuVo.getSpu().getId());
        orderItem.setSkuId(skuVo.getSku().getId());
        orderItem.setName(skuVo.getSku().getName());
        orderItem.setPrice(skuVo.getSku().getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(skuVo.getSku().getPrice()*num);
        orderItem.setPayMoney(skuVo.getSku().getPrice()*num);
        orderItem.setImage(skuVo.getSku().getImage());
        orderItem.setWeight(skuVo.getSku().getWeight());
        // 包邮
        orderItem.setPostFee(0);

        // 没有登录
        if(isLogin == null || isLogin.equals(0) ){

            boolean fal = false;

            // 判断cookie 是否存在数据
            Cookie[] cookies = request.getCookies();

            String cartJson =null ;

            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                // 购物车里面有数据
                if("cart".equals(name)){
                    fal = true;
                    cartJson = cookie.getValue();
                }
            }
            // 购物车里面有数据
            if(fal){

                // cartJson  转成list 集合
                ObjectMapper mapper = new ObjectMapper();
                try {
                    if(cartJson != null && !"".equals(cartJson)) {

                        String decodeCartJson = URLDecoder.decode(cartJson);

                        List<OrderItem> list = mapper.readValue(decodeCartJson, new TypeReference<List<OrderItem>>() { });
                        // 判断是否存在相同的商品
                        for (OrderItem item : list) {
                            Long skuId1 = item.getSkuId();
                            if(skuId.equals(skuId1)){
                                Integer newNum = num+ item.getNum();
                                // 存在相同的商品
                                item.setNum(newNum);
                                // 设置金额
                                item.setPostFee(newNum*item.getPrice());
                                item.setMoney(newNum*item.getPrice());


                                String newCartJson = mapper.writeValueAsString(list);
                                String encodeNewCartJson = URLEncoder.encode(newCartJson, "utf-8");
                                Cookie cookie = new Cookie("cart", encodeNewCartJson);
                                response.addCookie(cookie);
                                return Result.ok();
                            }
                        }
                        // 购物车中没有存在相同商品
                        list.add(orderItem);
                        String newCartJson = mapper.writeValueAsString(list);
                        String encodeNewCartJson = URLEncoder.encode(newCartJson, "utf-8");
                        Cookie cookie = new Cookie("cart", encodeNewCartJson);
                        response.addCookie(cookie);
                        return  Result.ok();

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 当购物里面没有数据的时候
            }else{

                try {
                    ObjectMapper mapper = new ObjectMapper();
                    ArrayList<OrderItem> orderItems = new ArrayList<>();
                    orderItems.add(orderItem);
                    String newCartJson = mapper.writeValueAsString(orderItems);
                    String encodeNewCartJson = URLEncoder.encode(newCartJson, "utf-8");
                    Cookie cookie = new Cookie("cart", encodeNewCartJson);
                    response.addCookie(cookie);
                    return Result.ok();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            /*
            try {
                String orderItemJson = mapper.writeValueAsString(orderItem);

                Cookie cookie = new Cookie("cart", orderItemJson);
                response.addCookie(cookie);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }*/
        }
       /*   if(user == null){ // 说明没有登录
            // 要把数据添加cookie 中
           *//* new Cookie();
            response.addCookie();*//*


        }
        */
        Integer i = 1;
        if( i.equals(isLogin)){
            //这里表示cookie中没有数据
            // 模拟登录用户数据 TODO
            user = new User();
            user.setUsername("admin");
            BoundHashOperations hashOperations = redisTemplate.boundHashOps("cart_" + user.getUsername());
            // 先获取对应的key 看是否存在数据
            Object o = hashOperations.get(skuId);
            if(o == null){
                //  不存在相同的商品
                hashOperations.put(skuId,orderItem);

            }else{
                // 存在相同的商品   需要进行覆盖
                OrderItem oi = (OrderItem)o;
                Integer newNum =  oi.getNum()+num;
                orderItem.setNum(newNum);
                orderItem.setPayMoney(newNum*orderItem.getPrice());
                orderItem.setMoney(newNum*orderItem.getPrice());
                hashOperations.put(skuId,orderItem);
            }


        }

        return Result.ok();
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("cookieToRedis/{username}")
    public String cookieToRedis( HttpServletRequest request, @PathVariable String username){
        // 判断cookie是否存在数据
        Cookie[] cookies = request.getCookies();
        boolean fal = false;
        String cartJson =null ;
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            // 购物车里面有数据
            if("cart".equals(name)){
                fal = true;
                cartJson = cookie.getValue();
            }
        }
        if(fal == true ){
            //存在数据
            // cartJson  转成list 集合
            try {
                ObjectMapper mapper = new ObjectMapper();
                if(cartJson != null && !"".equals(cartJson)) {
                    String decodeCartJson = URLDecoder.decode(cartJson);

                    List<OrderItem> list = mapper.readValue(decodeCartJson, new TypeReference<List<OrderItem>>() { });
                    // 判断是否存在相同的商品
                    BoundHashOperations hashOperations = redisTemplate.boundHashOps("cart_" + username);
                    // 把list 保存到用户购物车中
                    for (OrderItem orderItem : list) {
                        hashOperations.put(orderItem.getSkuId(),orderItem);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "";
    }
}
